package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import cn.jhc.bean.Article;
import cn.jhc.bean.User;
import cn.jhc.db.DbFactory;

/**
 * Servlet implementation class FrontServlet
 */
@WebServlet("/user/front.do")
public class FrontServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if(type == null) {
			type = "html";
		}
		String pageNum = request.getParameter("page");
		int page = 0;
		if(pageNum != null) {
			page = Integer.parseInt(pageNum);
		}
		
		User user = (User) request.getSession().getAttribute("currentUser");
		if(user == null) {
			response.sendRedirect("../login.jsp");
		} else {
			//找出当前用户所有消息，放入request范围
			List<Article> articles = DbFactory.getArticleDao().findByUser(user.getId(), page);
			if(type.equals("html")) {
				request.setAttribute("articles", articles);
				request.getRequestDispatcher("/WEB-INF/front.jsp").forward(request, response);				
			} else {
				response.setContentType("application/json; charset=utf8");
				PrintWriter out = response.getWriter();
				JSONArray array = new JSONArray(articles);
				out.println(array.toString());
			}
			
		}
	}

}
